<?php
App::uses('AppController', 'Controller');
/**
 * Deliveries Controller
 *
 * @property Delivery $Delivery
 */
class DeliveriesController extends AppController {

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Delivery->recursive = 0;
		$deliveries = $this->Delivery->find('all', array('conditions' => array('Delivery.archive' => '0')));
		$this->set(compact('deliveries'));
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Delivery->exists($id)) {
			throw new NotFoundException(__('Invalid delivery'));
		}
		$options = array('conditions' => array('Delivery.' . $this->Delivery->primaryKey => $id));
		$delivery = $this->Delivery->find('first', $options);
		
		$this->loadModel('Products');
		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');

		foreach($delivery['Ordersproducts'] as $i=>$j){
			$product = $this->Products->findById($j['products_id']);
			$delivery = Set::insert($delivery, 'Ordersproducts.'.$i.'.Products', $product['Products']);

			$brand = $this->Productsbrands->findById($product['Products']['productsbrands_id']);
			$delivery = Set::insert($delivery, 'Ordersproducts.'.$i.'.Brand', $brand['Productsbrands']);

			$range = $this->Productsranges->findById($product['Products']['productsranges_id']);
			if(empty($range)){$range = array('Productsranges' => array('name' => ''));}
			$delivery = Set::insert($delivery, 'Ordersproducts.'.$i.'.Range', $range['Productsranges']);

			$category = $this->Productscategories->findById($product['Products']['productscategories_id']);
			if(empty($category)){$category = array('Productscategories' => array('name' => ''));}
			$delivery = Set::insert($delivery, 'Ordersproducts.'.$i.'.Category', $category['Productscategories']);
		}

		foreach($delivery['Gift'] as $i=>$j){
			$product = $this->Products->findById($j['products_id']);
			$delivery = Set::insert($delivery, 'Gift.'.$i.'.Products', $product['Products']);

			$brand = $this->Productsbrands->findById($product['Products']['productsbrands_id']);
			$delivery = Set::insert($delivery, 'Gift.'.$i.'.Brand', $brand['Productsbrands']);

			$range = $this->Productsranges->findById($product['Products']['productsranges_id']);
			if(empty($range)){$range = array('Productsranges' => array('name' => ''));}
			$delivery = Set::insert($delivery, 'Gift.'.$i.'.Range', $range['Productsranges']);

			$category = $this->Productscategories->findById($product['Products']['productscategories_id']);
			if(empty($category)){$category = array('Productscategories' => array('name' => ''));}
			$delivery = Set::insert($delivery, 'Gift.'.$i.'.Category', $category['Productscategories']);
		}

		$this->set(compact('delivery'));
	}

/**
 * add method
 *
 * @return void
 *//*
	public function add() {
		if ($this->request->is('post')) {
			$this->Delivery->create();
			if ($this->Delivery->save($this->request->data)) {
				$this->Session->setFlash(__('The delivery has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The delivery could not be saved. Please, try again.'));
			}
		}
		$orders = $this->Delivery->Order->find('list');
		$this->set(compact('orders'));
	}*/

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	/*public function edit($id = null) {
		if (!$this->Delivery->exists($id)) {
			throw new NotFoundException(__('Invalid delivery'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Delivery->save($this->request->data)) {
				$this->Session->setFlash(__('The delivery has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The delivery could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Delivery.' . $this->Delivery->primaryKey => $id));
			$this->request->data = $this->Delivery->find('first', $options);
		}
		$orders = $this->Delivery->Order->find('list');
		$this->set(compact('orders'));
	}*/

/**
 * delete method
 *
 * @throws NotFoundException
 * @throws MethodNotAllowedException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Delivery->id = $id;
		if (!$this->Delivery->exists()) {
			throw new NotFoundException(__('Invalid delivery'));
		}
		$this->request->onlyAllow('post', 'delete');
		$data = array('id' => $id, 'archive' => '1');
		if ($this->Delivery->save($data)) {

			//archive deliveriesordersproduct
			$this->loadModel('Deliveriesordersproduct');
			$dop = $this->Deliveriesordersproduct->find('list', array('conditions'=>array('deliveries_id'=>$id)));
			foreach ($dop as $j) {
				$data = array('id' => $j, 'archive' => '1');
				$this->Deliveriesordersproduct->save($data);
			}

			$this->Session->setFlash(__('Delivery deleted'),'default', array('class' => 'savesuccess'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Delivery was not deleted'),'default', array('class' => 'saveerror'));
		$this->redirect(array('action' => 'index'));
	}

/**
 * chooseorder method
 *
 * @return void
 */
	public function chooseorder() {
		if ($this->request->is('post')) {
			$this->redirect(array('action' => 'delivery', $this->data['Deliveries']['orders_id']));
		}
		$orders = $this->Delivery->Orders->find('list', array('conditions' => array('Orders.status != 1',
																					'archive' => '0')));
		if(!empty($orders)){
			$this->set(compact('orders'));
		} else {
			$this->Session->setFlash(__('There is no orders incomplete'),'default', array('class' => 'saveerror'));
			$this->redirect(array('action' => 'index'));
		}

	}

/**
 * delivery method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delivery($id = null) {
		if ($this->request->is('post')) {
			print_r($this->data);

			//check if there is any receive quantity
			$empty = false;
			foreach($this->data['Delivery'] as $i => $j):
				if(!empty($this->data['Receive Quantity'][$i])){
					$empty = true;
				}
			endforeach;

			if(!$empty){
				$this->Session->setFlash(__('Order(s) was not received because there is no receive quantity.'),'default', array('class' => 'saveerror'));
				$this->redirect(array('action' => 'index'));
			}
			else{
				//print_r($this->request->data);
				$validate = true;

				foreach($this->data['Receive Quantity'] as $i => $j){
					if(!empty($j)){
						$data = array('Receive Quantity' => $j);
						$this->Delivery->set($data);

						if ($this->Delivery->validates()) {
						} else {
						    $validate = false;
						}
					}
				}

				$errors = $this->Delivery->invalidFields();
				//print_r($errors);

				if(!$validate){
					$this->Session->setFlash(__('Please enter only positive numbers for receive quantity.'),'default', array('class' => 'saveerror'));
				}
				else {
					//create new delivery
					$this->Delivery->create();
					$data = array('orders_id' => $id);
					$this->Delivery->save($data);
					$deliveryid = $this->Delivery->id;

					//loadModel that is needed
					$this->loadModel('Deliveriesordersproduct');
					$this->loadModel('Ordersproducts');
					$this->loadModel('Products');

					//save each deliveryorderproduct
					foreach($this->data['Delivery'] as $i => $j):
						if(!empty($this->data['Receive Quantity'][$i])){
							$data = array(	'ordersproducts_id' => $j,
											'deliveries_id'		=> $deliveryid,
											'deliveredQty'		=> $this->data['Receive Quantity'][$i]);
							$this->Deliveriesordersproduct->create();
							if($this->Deliveriesordersproduct->save($data)){
								
								//update orderproducts table and product onhand_level
								$orderproduct = $this->Ordersproducts->findById($j);

								$product = $this->Products->findById($orderproduct['Ordersproducts']['products_id']);
								$data = array(	'id' => $product['Products']['id'],
												'onhand_level' => $product['Products']['onhand_level'] + $this->data['Receive Quantity'][$i]);
								$this->Products->save($data);

								$data = array(	'id' => $j,
												'deliveredQty' => $orderproduct['Ordersproducts']['deliveredQty'] + $this->data['Receive Quantity'][$i]);
								$this->Ordersproducts->save($data);
								
							}

							
						}
					endforeach;

					$this->checkorder($id);

					$this->Session->setFlash(__('Order(s) was received.'),'default', array('class' => 'savesuccess'));
					$this->redirect(array('action' => 'view', $deliveryid));
				}
			}

		}

		$this->loadModel('Orders');
		$this->loadModel('Suppliers');
		$this->loadModel('Ordersproducts');
		$this->loadModel('Products');
		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');

		$order = $this->Orders->findById($id);		
		$suppliers = $this->Suppliers->findById($order['Orders']['suppliers_id']);		
		$ordersproducts = $this->Ordersproducts->find('all', array('conditions'=>array('orders_id' => $id)));

		foreach ($ordersproducts as $i => $j){
			
			$product = $this->Products->findById($j['Ordersproducts']['products_id']);
			$ordersproducts = Set::insert($ordersproducts, $i.'.Products', $product['Products']);
			
			$brand = $this->Productsbrands->findById($product['Products']['productsbrands_id']);
			$ordersproducts = Set::insert($ordersproducts, $i.'.Brands', $brand['Productsbrands']);

			$ranges = $this->Productsranges->findById($product['Products']['productsranges_id']);
			if(empty($ranges)){$ranges = array('Productsranges' => array('name' => ''));}
			$ordersproducts = Set::insert($ordersproducts, $i.'.Ranges', $ranges['Productsranges']);
			
			$categories = $this->Productscategories->findById($product['Products']['productscategories_id']);
			if(empty($categories)){$categories = array('Productscategories' => array('name' => ''));}
			$ordersproducts = Set::insert($ordersproducts, $i.'.Categories', $categories['Productscategories']);
		}
		$this->set(compact('ordersproducts', 'suppliers'));
	}

/**
 * checkorder method
 *
 * @return void
 */
	public function checkorder($id = null) {
		$this->loadModel('Orders');
		$this->loadModel('Ordersproducts');

		$order = $this->Orders->findById($id);
		$ordersproducts = $this->Ordersproducts->find('all', array('conditions'=>array('orders_id' => $id))); 

		$status = '1';
		if($order['Order']['status'] == '0'){
			$status = '2';
		} else if($order['Order']['status'] == '2'){
			foreach ($ordersproducts as $i => $j){
				if($j['Ordersproducts']['orderQty'] != $j['Ordersproducts']['deliveredQty']){
					$status = '2';
				}
			}
		}

		$data = array('id' => $id, 'status' => $status);
		$this->Orders->save($data);
	}

/**
 * editqty method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function editqty($id = null) {
		$this->loadModel('Deliveriesordersproducts');
		$this->loadModel('Ordersproducts');
		$this->loadModel('Products');
		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');

		$dop = $this->Deliveriesordersproducts->findById($id);
		$op = $this->Ordersproducts->findById($dop['Deliveriesordersproducts']['ordersproducts_id']);
		$product = $this->Products->findById($op['Ordersproducts']['products_id']);

		if ($this->request->is('post') || $this->request->is('put')) {
			print_r($this->request->data);

			$oriNum = $dop['Deliveriesordersproducts']['deliveredQty'];
			$changes = $oriNum - $this->request->data['Deliveriesordersproduct']['deliveredQty'];

			$prodata = array('id'=>$op['Ordersproducts']['products_id'], 'onhand_level'=>$product['Products']['onhand_level']-$changes);

			if($this->Products->save($prodata)){
				$opdata = array('id'=> $op['Ordersproducts']['id'],'deliveredQty'=>$op['Ordersproducts']['deliveredQty']-$changes);

				if($this->Ordersproducts->save($opdata)){
					$dopdata = array('id' => $dop['Deliveriesordersproducts']['id'], 'deliveredQty' => $dop['Deliveriesordersproducts']['deliveredQty']-$changes);

					if($this->Deliveriesordersproducts->save($dopdata)){
						$this->checkorder($op['Ordersproducts']['orders_id']);
						$this->Session->setFlash(__('The delivery quantity has been saved'),'default', array('class' => 'savesuccess'));
						$this->redirect(array('action' => 'view', $dop['Deliveriesordersproducts']['deliveries_id']));
					}
				}
			}
			else{
				$this->Session->setFlash(__('The delivery quantity could not be saved. Please, try again.'),'default', array('class' => 'saveerror'));
			}
		}

		$this->set(compact('dop', 'op', 'product'));
	}
}
